﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using MySql.Data.MySqlClient;

namespace DbCodeGenerator
{
    class MysqlDbHandle:IDbHandle
    {
        public string ServerAddress { get; set; }
        public string UserID { get; set; }
        public string Password { get; set; }
        public uint Port { get; set; }

        public IDbConnection getDbConnection()
        {
            MySqlConnectionStringBuilder sqlBuilder = new MySqlConnectionStringBuilder();
            sqlBuilder.Server = ServerAddress;
            sqlBuilder.UserID = UserID;
            sqlBuilder.Password = Password;
            sqlBuilder.Port = Port;
            return new MySqlConnection(sqlBuilder.ConnectionString);
        }
        public IDbConnection getDbConnection(string dbNmae)
        {
            MySqlConnectionStringBuilder sqlBuilder = new MySqlConnectionStringBuilder();
            sqlBuilder.Server = ServerAddress;
            sqlBuilder.UserID = UserID;
            sqlBuilder.Password = Password;
            sqlBuilder.Port = Port;
            sqlBuilder.Database = dbNmae;
            return new MySqlConnection(sqlBuilder.ConnectionString);
        }
        public DataTable getDatabases()
        {

            DataTable dt = null;
            using (MySqlConnection mysqlconn = (MySqlConnection)getDbConnection())
            {
                mysqlconn.Open();
                dt = mysqlconn.GetSchema("Databases");
                mysqlconn.Close();
            }
            return dt;
        }
        public DataTable getTables(string dbname)
        {
            DataTable dt = null;
            using (MySqlConnection mysqlconn = (MySqlConnection)getDbConnection(dbname))
            {
                mysqlconn.Open();
                dt = mysqlconn.GetSchema("Tables", new string[] { null, null, null, "BASE TABLE" });
                mysqlconn.Close();
            }
            return dt;
        }
        public DataTable getColumns(string dbname, string tabname) {
            DataTable dt = null;
            using (MySqlConnection mysqlconn = (MySqlConnection)getDbConnection(dbname))
            {
                mysqlconn.Open();
                dt = mysqlconn.GetSchema("Columns", new string[] { null, null, tabname });
                mysqlconn.Close();
            }
            return dt;
        }
    }
}
